/**
 * 初始化整体流量图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrnumber = require('echarts/util/number');

    var myChart1 = ec.init(document.getElementById('consumeCateOne')); 
    var myChart2 = ec.init(document.getElementById('consumeCateTwo'));

    var option_1 = {
        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc
        },
        legend: {
            selectedMode:true,
            data:[]
        },
        toolbox: {
            show : true,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: false},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y: 60,
            y2:15
        },
        dataZoom: {
            show: false,
            realtime : true
        },        
        xAxis: [{
            type: "category",
            position:'top',
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value.substr(0,4)+"-"+value.substr(5,2)+"-"+value.substr(8,2);
            }}
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '精准现金',
                type: 'line',
                data:[]
            }
        ]
    };

   var option_2 = {
        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc
        },
        legend: {
            y: 'bottom',
            selectedMode:true,
            data:[]
        },
        toolbox: {
            show : false,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: false},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y: 35,
            y2:60
        },        
        dataZoom: {
            show: true,
            y: 0,
            height: 20,
            realtime : true,
            start: 90
        },        
        xAxis: [{
            type: "category",
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value.substr(0,4)+"-"+value.substr(5,2)+"-"+value.substr(8,2);
            }}
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '精准现金',
                type: 'line',
                data:[]
            }
        ]
    };

    var colorArray= ['#ff7f50', '#87cefa', '#da70d6', '#32cd32', '#6495ed', 
                    '#ff69b4', '#ba55d3', '#cd5c5c', '#ffa500', '#40e0d0', 
                    '#1e90ff', '#ff6347', '#7b68ee', '#00fa9a', '#ffd700', 
                    '#6b8e23', '#ff00ff', '#3cb371', '#b8860b', '#30e0e0'];
    var colorIndex = 0;

    var EN_2_CN_Map = {"consume_cycle":"消耗周期","consume":"消耗","deposit":"充值","balance":"余额"};
    //[cate1, cate2]
    var cateArr = [];
    var indexArr = [];
    // 上下图例一一映射
    var legendMap  = {}; 

    function setLegendNameMap(cateArr_tmp,indexArr_tmp){
        cateArr = cateArr_tmp;
        indexArr = indexArr_tmp;
        option_1.legend.data = [];
        option_2.legend.data = [];
        legendMap = {};
        $.each(cateArr,function(i,cate){
            var cate_index_1 = cate+EN_2_CN_Map[indexArr[0]];
            var cate_index_2 = cate+EN_2_CN_Map[indexArr[1]];
            option_1.legend.data.push(cate_index_1);
            option_2.legend.data.push(cate_index_2);
            legendMap[cate_index_1] = cate_index_2;
            legendMap[cate_index_2] = cate_index_1;
        });
    }
    
    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(businessName,eventType){
        var dateGrp = $('#consumCateOpt').attr('dateGrp');
        var statType = $('#consumCateOpt').attr('statType');

        var indexArr_tmp = $("#consume_cate_indexs").val().split(",");
        var cateArr_tmp = $('#consume_cates').val().split(",");
        if(cateArr_tmp.length == 0){
            alert("必须选择对比城市!");
            return;
        }
        if(indexArr_tmp.length != 2){
            alert("请选择两个指标!");
            return;
        }

        setLegendNameMap(cateArr_tmp,indexArr_tmp);
        myChart1.showLoading({ text: '正在努力的读取数据中...' });
        myChart2.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/income/ajax/cateConsume',
            type: 'post',
            async: true,
            data:{"businessName":businessName,"dateGroup":dateGrp,"statType":statType, "consume_cates":$("#consume_cates").val(), "index1":indexArr[0],"index2":indexArr[1],"dataType":"chart"},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_1.xAxis[0].data = data.time;
                option_2.xAxis[0].data = data.time;
              
                var series_local_1 = [];
                var series_local_2 = [];

                $.each(cateArr,function(i,cate){
                      //上图每条曲线
                    series_local_1[i] = {
                        name: option_1.legend.data[i],
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        data: data[cate+"_"+indexArr[0]],
                        itemStyle: {normal: { color: colorArray[colorIndex % 20] }},
                    };
                    if(EN_2_CN_Map[indexArr[0]] == "消耗周期"){
                        series_local_1[i].markLine = { 
                            itemStyle:{normal:{color:'#dc143c'}},
                            data : [[{name: '起点', value: '60', xAxis: -1, yAxis: 60},{name: '终点',xAxis: data.time.length, yAxis: 60} ]]
                        };
                    }
                    //下图每条曲线
                    series_local_2[i] = {
                        name: option_2.legend.data[i],
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        data: data[cate+"_"+indexArr[1]],
                         itemStyle: {normal: { color: colorArray[colorIndex++ % 20] }},
                    };
                });

                option_1.series = series_local_1;
                option_2.series = series_local_2;     

                //区域缩放
                var datezoom_local={
                    stat_date:{start:(1-31/data.time.length)*100,end:100},
                    week_begin:{start:(1-12/data.time.length)*100,end:100},
                    month_num:{start:0,end:100},
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
                        stat_date:{start:0,end:100},
                        week_begin:{start:0,end:100},
                        month_num:{start:0,end:100},
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('stat_date'==dateGrp || 'week_begin'==dateGrp){    	
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }else if('month_num'==dateGrp){
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }
                    option_1.dataZoom.start=datezoom_local[dateGrp].start;
                    option_1.dataZoom.end=datezoom_local[dateGrp].end;
                    option_2.dataZoom.start=datezoom_local[dateGrp].start;
                    option_2.dataZoom.end=datezoom_local[dateGrp].end;
                    if(eventType == 1 && myChart2.component.dataZoom){
                        myChart1.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                        myChart2.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
                        option_2.dataZoom.show=true;
                    }
                    myChart1.setOption(option_1,true);
                    myChart2.setOption(option_2,true);
                }
                // myChart.clear();
                myChart1.connect(myChart2);
                myChart2.connect(myChart1);
                myChart1.hideLoading();
                myChart2.hideLoading();
            },
            error : function() {
                myChart1.hideLoading();
                myChart2.hideLoading();
            }
        });
    }

    //图例选择事件
    var ecConfig = require('echarts/config');
    function changeLegend_1(param){
        var selectedMap = param.selected;
        var target = param.target;
        var another = legendMap[target];
        myChart2.component.legend.setSelected(another,selectedMap[target]);
    }
    myChart1.on(ecConfig.EVENT.LEGEND_SELECTED, changeLegend_1);

    function changeLegend_2(param){
        var selectedMap = param.selected;
        var target = param.target;
        var another = legendMap[target];
        myChart1.component.legend.setSelected(another,selectedMap[target]);
    }
    myChart2.on(ecConfig.EVENT.LEGEND_SELECTED, changeLegend_2);

    //鼠标click事件
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }else{
            return ;
        }
        loadTableData(click_date);
    }
    myChart1.on(ecConfig.EVENT.CLICK, eventClick);
    myChart2.on(ecConfig.EVENT.CLICK, eventClick);
    //加载27个直销城市当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"cate_name":0,"balance":1,"consume":1,"deposit":1,"consume_cycle":1};
    function loadTableData(stat_date){
        var dateGrp = $('#consumCateOpt').attr('dateGrp');
        var statType = $('#consumCateOpt').attr('statType');
        var businessName = cate;
        $.ajax({
            url: '/dashboard/income/ajax/cateConsume',
            type: 'post',
            async: true,
            data:{"dateGroup":dateGrp,"statType":statType,"dateVal":stat_date, "businessName":businessName,"dataType":"table"},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var htmlRows = "";
                $.each(resultList,function(i,vo){
                    htmlRows += "<tr>";

                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += zrnumber.addCommas(vo[col]);
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#consumeCateTable tr:gt(0)').remove();
                $('#consumeCateTable_date').text(stat_date.replace(/\-/g,"."));
                $('#consumeCateTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }

    //提示框
    function  tooltipFunc(params, ticket, callback){
        var dateVal = formatShowDate(params[0].name);
        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        if(isDay())
            result += getWeekDay(dateVal);
        result += '</td><td>占比</td></tr>';
        var total=0;
        $(params).each(function(index,para){
            total+=para.data;
        });
        $(params).each(function(index,para){
            var s=((para.data/total)*100).toFixed(2);
            result+='<tr><td>'+para[0]+'</td><td>'+zrnumber.addCommas(para.data)+'</td><td>'+s+'%</td></tr>';
        });
        result+='</table>';
        return result;
    }           

    var zrUtil = require('zrender/tool/util');

    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }

    function formatTime(time){
        return time;
    }


    function formatShowDate(yyyymmdd){
        var dateGrp = $('#consumCateOpt').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#consumCateOpt').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

    function getShowDays(){
        return xAxis_show;
    }

    function getAllDays(){
        return option_2.xAxis.data||option_2.xAxis[0].data;
    }

    //绑定书刷新按钮点击事件
    $("#refreshConsumeCate_btn").click(function(){
        var type = 2;      
        EC.show(cate,type);
    });


    $(function(){
        $("#consume_cate_mul").multiselect({
            header:false,
            height:300,
            minWidth:140,
            noneSelectedText: "--请选择--",
            checkAllText: "disabled",
            uncheckAllText: '清空',
            selectedList:2,
            click: function(event, ui){
                var array_of_checked_values = $("#consume_cate_mul").multiselect("getChecked").map(function(){
                   return this.value;    
                }).get();
                var warning = $(".message");
                if(array_of_checked_values.length > 3){
                    return false;
                }
                 // $("#consume_cates").val(array_of_checked_values.join(","));
            },
            uncheckAll: function(){
                $("#consume_cates").val('');
            },
            selectedText: function(numChecked, numTotal, checkedItems){
                var two='';
                /*
                    js数组的map方法和 $.map(arr,callback)将一个数组中的元素转换到另一个数组中;
                    $(selector).map(arr,callback)返回jquery对象 $(selector).map(arr,callback).get()使用 get() 来处理返回的对象以得到基础的数组
                */
               if(numChecked > 3){
                        return false;
                }               
                var idcs=checkedItems.map(function(element){
                    return element.value; 
                });
                $("#consume_cates").val(idcs.join(','));
                return idcs.join(' , ');
            }
       });
    }); 

    $(function(){
        $("#consCate_index_mul").multiselect({
            header:false,
            height:120,
            minWidth:140,
            noneSelectedText: "--请选择--",
            checkAllText: "disabled",
            uncheckAllText: '清空',
            selectedList:2,
            click: function(event, ui){
                var array_of_checked_values = $("#consCate_index_mul").multiselect("getChecked").map(function(){
                   return this.value;    
                }).get();
                var warning = $(".message");
                if(array_of_checked_values.length > 2){
                    return false;
                }
                // $("#consume_cate_indexs").val(array_of_checked_values.join(","));
            },
            uncheckAll: function(){
                $("#consume_cate_indexs").val('');
            },
            selectedText: function(numChecked, numTotal, checkedItems){
               if(numChecked > 2){
                    return false;
                }               

                var checkedVal = checkedItems.map(function(element){
                    return element.value; 
                }).join(',');
                $("#consume_cate_indexs").val(checkedVal);

                var idcs=checkedItems.map(function(element){
                    // console.log(element.value);
                    return element.labels[0].innerText; 
                }).join(' , ');                
                return idcs;
            }
       });
    });


    // $(":button.btnConsumeCate[dateGrp]").click(function(){
    //     changeDateGrp(this);       
    //     EC.show(cate,1);
    // });

    var EC={
        show:show,
        resize:function(){myChart1.resize();myChart2.resize();},
        getShowDays:getShowDays,
        getAllDays:getAllDays
    };

    return EC;
});

